/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;

import app.TaskPooler;
import base.UserPreferences;
import exception.RepositoryException;
import facade.Facade;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author tacio
 */
public class JFeedsUSysTray {

    private static Facade facade;
    private static UserPreferences preferences;
    private static TaskPooler taskpooler;
    private static boolean isServiceRunning = false;

    static{
        try {
            facade = Facade.getFacade();
            preferences = facade.getUserPreferences();
        } catch (RepositoryException ex) {
            Logger.getLogger(JFeedsUSysTray.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public JFeedsUSysTray(){
        try {
            facade = Facade.getFacade();
            preferences = facade.getUserPreferences();
        } catch (RepositoryException ex) {
            Logger.getLogger(JFeedsUSysTray.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void  updatePreferences(){
        try {
            preferences = facade.getUserPreferences();
        } catch (RepositoryException ex) {
            Logger.getLogger(JFeedsUSysTray.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) {
        /* Use an appropriate Look and Feel */
        try {
//            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
//            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (UnsupportedLookAndFeelException ex) {
            ex.printStackTrace();
        } catch (IllegalAccessException ex) {
            ex.printStackTrace();
        } catch (InstantiationException ex) {
            ex.printStackTrace();
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }

        /* Turn off metal's use of bold fonts */
        UIManager.put("swing.boldMetal", Boolean.FALSE);
        //Schedule a job for the event-dispatching thread:
        //adding TrayIcon.
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                createAndShowGUI();
            }
        });

    }

    private static void createAndShowGUI() {

//        boolean isServiceRunning = false;

        //Check the SystemTray support
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon =
                new TrayIcon(createImage("images/tvIcon.jpg", "tray icon"));
        trayIcon.setImageAutoSize(true);
        final SystemTray tray = SystemTray.getSystemTray();


        // Create a popup menu components
        MenuItem controlPanelItem = new MenuItem("Control Panel");
        MenuItem startStopServiceItem = new MenuItem("Start Service");        
        MenuItem aboutItem = new MenuItem("About JFeeds-U");
        MenuItem exitItem = new MenuItem("Exit");

//        CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
//        CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
//        Menu displayMenu = new Menu("Display");
//        MenuItem errorItem = new MenuItem("Error");
//        MenuItem warningItem = new MenuItem("Warning");
//        MenuItem infoItem = new MenuItem("Info");
//        MenuItem noneItem = new MenuItem("None");
        

        //Add components to popup menu
        popup.add(controlPanelItem);
        popup.addSeparator();
        popup.add(startStopServiceItem);
        popup.addSeparator();
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(exitItem);

        trayIcon.setPopupMenu(popup);

        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            return;
        }

        trayIcon.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    JFeedsUMain controlPanel = JFeedsUMain.class.newInstance();
                    controlPanel.setVisible(true);
                } catch (InstantiationException ex) {
                    Logger.getLogger(JFeedsUSysTray.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(JFeedsUSysTray.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        controlPanelItem.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    JFeedsUMain controlPanel = JFeedsUMain.class.newInstance();
                    controlPanel.setVisible(true);
                } catch (InstantiationException ex) {
                    Logger.getLogger(JFeedsUSysTray.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalAccessException ex) {
                    Logger.getLogger(JFeedsUSysTray.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

        startStopServiceItem.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                updatePreferences();
                if (!isServiceRunning) {                                            
                        taskpooler = new TaskPooler(preferences.getTaskPoolerRepeatInterval().intValue());
                        taskpooler.getTimer().schedule(taskpooler, 0, taskpooler.getRepeatInterval());
                        MenuItem item = (MenuItem) e.getSource();
                        item.setLabel("Stop Service");
                        isServiceRunning = true;
                        trayIcon.setImage(createImage("images/tvIconRunning.jpg", "Service Running tray icon"));
                } else {
                    taskpooler.stop();
                    MenuItem item = (MenuItem) e.getSource();
                    item.setLabel("Start Service");
                    isServiceRunning = false;
                    trayIcon.setImage(createImage("images/tvIconStopped.jpg", "Service Stopped tray icon"));
                }
            }
        });

       
        aboutItem.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                
                    AboutJFeedsU aboutWindow = new AboutJFeedsU(null, true);
                    aboutWindow.setVisible(true);
                
            }
        });

     

        ActionListener listener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                MenuItem item = (MenuItem)e.getSource();
                //TrayIcon.MessageType type = null;
                System.out.println(item.getLabel());
                if ("Error".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.ERROR;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an error message", TrayIcon.MessageType.ERROR);

                } else if ("Warning".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.WARNING;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is a warning message", TrayIcon.MessageType.WARNING);

                } else if ("Info".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.INFO;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an info message", TrayIcon.MessageType.INFO);

                } else if ("None".equals(item.getLabel())) {
                    //type = TrayIcon.MessageType.NONE;
                    trayIcon.displayMessage("Sun TrayIcon Demo",
                            "This is an ordinary message", TrayIcon.MessageType.NONE);
                }
            }
        };

      
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                tray.remove(trayIcon);
                System.exit(0);
            }
        });
    }

    //Obtain the image URL
    protected static Image createImage(String path, String description) {
        URL imageURL = JFeedsUSysTray.class.getResource(path);

        if (imageURL == null) {
            System.err.println("Resource not found: " + path);
            return null;
        } else {
            return (new ImageIcon(imageURL, description)).getImage();
        }
    }
}
